package com.flowable.controller;

import org.flowable.engine.HistoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.variable.api.history.HistoricVariableInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/api/processes")
public class ProcessDetailController {

    @Autowired
    private HistoryService historyService;
    
    @Autowired
    private RuntimeService runtimeService;

    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final SimpleDateFormat DATE_ONLY_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 获取流程实例详情及历史记录
     */
    @GetMapping("/{processId}/detail")
    public Map<String, Object> getProcessDetail(@PathVariable String processId) {
        Map<String, Object> result = new HashMap<>();
        
        // 1. 获取流程实例基本信息
        HistoricProcessInstance historicProcess = historyService.createHistoricProcessInstanceQuery()
                .processInstanceId(processId)
                .singleResult();
        
        if (historicProcess == null) {
            // 检查是否是运行中的流程实例
            ProcessInstance runtimeProcess = runtimeService.createProcessInstanceQuery()
                    .processInstanceId(processId)
                    .singleResult();
            if (runtimeProcess == null) {
                result.put("success", false);
                result.put("message", "流程实例不存在");
                return result;
            }
            // 处理运行中的流程实例
            fillProcessInfo(result, runtimeProcess);
        } else {
            // 处理已结束的历史流程实例
            fillProcessInfo(result, historicProcess);
        }
        
        // 2. 获取流程历史记录（活动节点）
        List<Map<String, Object>> historyList = getProcessHistory(processId);
        result.put("history", historyList);
        
        result.put("success", true);
        return result;
    }
    
    /**
     * 填充流程实例基本信息
     */
    private void fillProcessInfo(Map<String, Object> result, HistoricProcessInstance process) {
        result.put("processId", process.getId());
        result.put("applicant", getProcessVariable(process.getId(), "applicant")); // 申请人
        result.put("days", getProcessVariable(process.getId(), "days")); // 请假天数
        result.put("startTime", DATE_FORMAT.format(process.getStartTime())); // 流程开始时间
        result.put("status", process.getEndTime() != null ? "已结束" : "进行中");// 流程状态
        
        // 请假原因
        result.put("reason", getProcessVariable(process.getId(), "reason"));
        // 请假开始日期
        result.put("startDate", getProcessVariable(process.getId(), "startDate"));
        // 请假结束日期
        result.put("endDate", getProcessVariable(process.getId(), "endDate"));

        System.err.println(result);
    }
    
    /**
     * 填充运行中流程实例的基本信息
     */
    private void fillProcessInfo(Map<String, Object> result, ProcessInstance process) {
        result.put("processId", process.getId());
        result.put("applicant", getProcessVariable(process.getId(), "applicant"));
        result.put("days", getProcessVariable(process.getId(), "days"));
        result.put("startTime", DATE_FORMAT.format(process.getStartTime()));
        result.put("status", "进行中");
        
        result.put("reason", getProcessVariable(process.getId(), "reason"));
        result.put("startDate", getProcessVariable(process.getId(), "startDate"));
        result.put("endDate", getProcessVariable(process.getId(), "endDate"));
    }
    
    /**
     * 获取流程变量
     */
    private Object getProcessVariable(String processId, String variableName) {
        try {
            // 先从历史变量中查询
            HistoricVariableInstance variable = historyService.createHistoricVariableInstanceQuery()
                    .processInstanceId(processId)
                    .variableName(variableName)
                    .singleResult();
            
            if (variable != null) {
                return variable.getValue();
            }
            
            // 历史变量中没有则查询运行时变量
            return runtimeService.getVariable(processId, variableName);
        } catch (Exception e) {
            return ""; // 变量不存在时返回空字符串
        }
    }
    
    /**
     * 获取流程历史记录（活动节点）
     */
    private List<Map<String, Object>> getProcessHistory(String processId) {
        List<Map<String, Object>> historyList = new ArrayList<>();
        
        // 查询流程所有活动节点历史
        List<HistoricActivityInstance> activities = historyService.createHistoricActivityInstanceQuery()
                .processInstanceId(processId)
                .orderByHistoricActivityInstanceStartTime().asc()
                .list();
        
        for (HistoricActivityInstance activity : activities) {
            Map<String, Object> historyItem = new HashMap<>();
            
            // 根据活动类型和ID确定步骤名称
            String stepName = getStepName(activity);
            historyItem.put("step", stepName);
            
            // 处理时间
            if (activity.getEndTime() != null) {
                historyItem.put("time", DATE_FORMAT.format(activity.getEndTime()));
                historyItem.put("status", "完成");
            } else if (activity.getStartTime() != null) {
                historyItem.put("time", DATE_FORMAT.format(activity.getStartTime()));
                historyItem.put("status", "进行中");
            } else {
                historyItem.put("time", "");
                historyItem.put("status", "未开始");
            }
            
            historyList.add(historyItem);
        }
        
        return historyList;
    }
    
    /**
     * 根据活动实例获取步骤名称
     */
    private String getStepName(HistoricActivityInstance activity) {
        // 优先使用活动名称
        if (activity.getActivityName() != null && !activity.getActivityName().isEmpty()) {
            return activity.getActivityName();
        }
        
        // 根据活动类型和ID生成名称
        switch (activity.getActivityType()) {
            case "startEvent":
                return "流程开始";
            case "userTask":
                return "用户任务";
            case "endEvent":
                return "流程结束";
            default:
                return activity.getActivityId();
        }
    }
}
    